/**
 * Created by zzy on 2017/9/26.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    StyleSheet,
    ScrollView,
    PixelRatio,
    WebView,
    Dimensions,
    InteractionManager,
    DeviceEventEmitter
} from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons'
import NetRequestLuo from '../util/NetRequest'
import ProductCellH from '../componentluo/ProductCellH'
import ShopCell from '../../luojs/componentluo/shopcell'
import Toast from 'react-native-easy-toast'
import shoppingCartStore from '../store/ShoppingCartStore'
import DataUtil from '../util/DataUtil'
import LoadingView from '../../js/component/LoadingView'
import Constant from '../../js/Contant'
import addressMgrStore from '../../js/store/AddrMgrStore'

var ScrollableTabView = require('react-native-scrollable-tab-view');

export default class Collection extends Component{
    static navigationOptions = {
        title: '收藏'
    };
    constructor(props){
        super(props);
        this.state={
            productItemCommonModel:[],
            shopBasicInfoModel:[],
            loading:true
        }
    }
    render(){
        return <View style={{flex: 1,backgroundColor: 'white'}}>
            <LoadingView
                visible={this.state.loading}
                color="white"
                indicatorSize="small"
                messageFontSize={12}
                message=''
            />
            <ScrollableTabView initialPage={0}
                               renderTabBar={()=> <HeadView {...this.props}/>}
                               style={{height:90}}
                               tabBarActiveTextColor='#4dc0ff'
                               tabBarInactiveTextColor='#333333'
                               tabBarUnderlineStyle={{backgroundColor:'#4dc0ff',height:2,width:10}}>
                <ProductCollectList tabLabel='商品' productList={this.state.productItemCommonModel} {...this.props}/>
                <ShopCollectList tabLabel='店铺' shopList={this.state.shopBasicInfoModel} {...this.props}/>
            </ScrollableTabView>
        </View>
    }

    componentDidMount() {
        this.getData();
        this.loginin = DeviceEventEmitter.addListener(Constant.LOGINOK,this.getData.bind(this));
    }
    getData(){
        this.shopCollectList();
        this.productCollectList();
    }
    componentWillUnmount(){
        this.loginin.remove();
    };
    shopCollectList(){
        let shopParam={
              type:'shop',
              latitude: addressMgrStore.activeAddress.latitude,
              longtitude: addressMgrStore.activeAddress.longitude,
        };
        InteractionManager.runAfterInteractions(()=> {
            NetRequestLuo.collectList(shopParam).then((data)=>{
                LOG('店铺收藏列表-----------'+JSON.stringify(data));
                if(data.shopBasicInfoModel==null){
                    return;
                }
                this.setState(
                    {
                        shopBasicInfoModel:data.shopBasicInfoModel,
                        loading:false
                    })

            }).catch(err=>{
                this.setState(
                    {
                        loading:false
                    }
                );
                this.props.navigation.navigate('Login');
            })
        })
    }
    productCollectList(){
        let proParam={
            type:'product'
        };
        InteractionManager.runAfterInteractions(()=> {
            NetRequestLuo.collectList(proParam).then((data)=>{
                LOG('商品收藏列表-----------'+JSON.stringify(data));
                if(data.productItemCommonModel==null){
                    return;
                }
                this.setState(
                    {
                        productItemCommonModel:data.productItemCommonModel,
                        loading:false
                    })

            })
        })
    }
}
class ShopCollectList extends Component{
    render(){
        let {shopList}=this.props;

        return <View style={{flex:1}}>
            {
                shopList.length==0?<View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
                    <Text>暂无收藏</Text>
                </View>:<View style={{flex:1}}>
                        {
                            shopList.map((shop,index)=>{
                                return <ShopCell shop={shop} key={index} callback={()=>{
                                    this.props.navigation.navigate('WaterStation',{shopId:shop.shopId});
                                }
                                }/>
                            })
                        }
                    </View>

            }
            </View>
    }
}
class ProductCollectList extends Component{
    render(){
        let {productList}=this.props;
        return <View style={{flex:1,justifyContent:'center'}}>
            {
                productList.length==0?<Text style={{flex:0,alignSelf:'center'}}>暂无收藏</Text>
                    :<View style={{flex:1}}>
                    {
                        productList.map((product,index)=>{
                            return <ProductCell item={product} key={index} callback={()=>{
                                this.props.navigation.navigate('ProductsDetailsLuo',{productItemId:product.productItemModels[0].productItemId,shopId:product.shopId});
                            }}
                            addToShoppingCart={this._addToShoppingCart.bind(this)}/>
                        })
                    }

                </View>
            }
            <Toast ref="toast" position='bottom'/>
        </View>

    }
    _addToShoppingCart(item){
        let param={
            productItemId: item.productItemModels[0].productItemId,
            productType: item.type,
            shopId: item.shopId,
        };
        NetRequestLuo.addShoppingCart(param,'increase').then((data)=>{
            LOG('加入购物车--------'+JSON.stringify(data));
            shoppingCartStore.getShoppingCart();
            DeviceEventEmitter.emit('refreshShopList');//刷新购物车
            this.refs.toast.show('已加入购物车');
        })
    }
}
class ProductCell extends Component{
    render(){
        let {name,showPrice,soldNumber,imageUrl} = this.props.item;
        let {currentPrice,saleMount,productType} = this.props.item.productItemModels[0];
        let {addToShoppingCart,callback} = this.props;
        var image=productType=='水票'?require('../../luoasserts/tiket/goods_ticket_bg.png'):{uri:imageUrl};
        return <TouchableOpacity style={[{flexDirection:'row',justifyContent:'space-between',backgroundColor:'#fff',borderBottomColor:'#f5f5f5',
            borderBottomWidth:1/PixelRatio.get()}]} onPress={callback} activeOpacity={0.9}>
            <View style={{flexDirection:'row'}}>
                <Image style={{marginVertical:5,marginLeft:5,width:80,height:80}} resizeMode={'contain'} source={image}/>
                <View style={{justifyContent:'space-around',marginLeft:5}}>
                    <Text style={{fontWeight:'100'}}>{name}</Text>
                    <Text style={{color:'red'}}>¥{DataUtil.f2y(currentPrice)}</Text>
                    <Text style={{fontSize:12,color:'gray'}}>已售{saleMount+''}</Text>
                </View>
            </View>
            <View style={{justifyContent:'center',marginRight:15}}>
                <TouchableOpacity onPress={()=>{
                    addToShoppingCart(this.props.item)
                }}>
                    <Ionicons name="ios-cart-outline" size={24} color="red"/>
                </TouchableOpacity>
            </View>
        </TouchableOpacity>
    }
}

const HeadView = React.createClass({
    propType: {
        goToPage: React.PropTypes.func,
        activeTab: React.PropTypes.number,
        tabs: React.PropTypes.array,
        tabStyle: View.propTypes.style,
        underlineStyle: View.propTypes.style,
    },
    render(){
        const backS = {
            flexDirection:'row',
            height:50,
            alignItems:'center',
            flex:1,
        };
        const btnS = {
            height:35,
            justifyContent:'center',
            alignItems:'center',
            flex:1
        };
        const {goBack} = this.props.navigation;
        return <View style={{flexDirection:'row',alignItems:'center'}}>
            <View style={backS}>
                {this.props.tabs.map((tab, i)=> {
                    let textColor = this.props.activeTab==i ? '#4dc0ff' : '#333333';
                    let lineColor = this.props.activeTab==i ? '#4dc0ff' : '#ffffff';
                    return <TouchableOpacity style={btnS}
                                             activeOpacity={1}
                                             onPress={()=>{
                                                 this.props.goToPage(i)
                                             }}
                                             key={tab}>
                        <Text style={{color:textColor}}>{tab}</Text>
                        <View style={{position: 'absolute',backgroundColor:lineColor,width:2000,height:2,bottom: 0}}></View>
                    </TouchableOpacity>
                })}
            </View>

        </View>
    }
});